package com.dwx.guli.service.sms.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.dwx.guli.service.base.exception.GuliException;
import com.dwx.guli.service.base.result.ResultCodeEnum;
import com.dwx.guli.service.sms.service.SmsService;
import com.dwx.guli.service.sms.util.SmsProperties;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private SmsProperties smsProperties;
    @Override
    public void sendSms(String mobile, String checkCode) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai",
                smsProperties.getKeyId(),
                smsProperties.getKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", smsProperties.getSignName());
        request.putQueryParameter("TemplateCode", smsProperties.getTemplateCode());
        Gson gson=new Gson();
        Map<String ,String > map =new HashMap<>();
        map.put("code",checkCode);
        String json = gson.toJson(map);
        request.putQueryParameter("TemplateParam", json);
        CommonResponse response=null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            log.error("短信发送失败：" + ExceptionUtils.getStackTrace(e));
            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR);
        }
        String data = response.getData();
        HashMap<String ,String> resultMap = gson.fromJson(data, HashMap.class);
        String code = resultMap.get("Code");
        String message = resultMap.get("Message");
        if("isv.BUSINESS_LIMIT_CONTROL".equals(code)){
            log.error("短信发送过于频繁：code = " + code + "，message = " + message);
            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR_BUSINESS_LIMIT_CONTROL);
        }

        if(!"OK".equals(code)){
            log.error("短信发送失败：code = " + code + "，message = " + message);
            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR);
        }
    }
}
